<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :model="searchForm" :inline="true">
				<el-form-item label="角色类型">
					<el-input v-model="searchForm.typeName" placeholder="角色类型"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="warning" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-permission="'role:insert'"  @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表v-loading="listLoading"-->
		<el-table :data="tableDatas" v-loading="listLoading" @selection-change="handleSelectionChange" highlight-current-row
			style="width: 100%;">
			<!--多选框-->
			<el-table-column type="selection" >
			</el-table-column>
			<el-table-column type="index"  align="center"  label="序号">
			</el-table-column>
      <el-table-column prop="name" align="center" label="角色" >
      </el-table-column>
      <el-table-column  prop="sn" align="center" label="编号" >
      </el-table-column>
      <el-table-column  show-overflow-tooltip align="center" label="菜单" >
        <template scope="scope">
          <span>{{scope.row.menus.map(m=>m.name)}}</span>
        </template>
      </el-table-column>
      <el-table-column  show-overflow-tooltip align="center" label="权限" >
        <template scope="scope">
          <span>{{scope.row.permissions.map(m=>m.name)}}</span>
        </template>
      </el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" v-permission="'role:insert'" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button type="danger" v-permission="'role:delete'" size="small" @click="handleDel(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" :disabled="this.sels.length === 0" v-permission="'role:delete'" @click="handlePatchDel">批量删除</el-button>
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
				:page-sizes="[5, 10, 15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
				:total="totals" style="float:right;">
			</el-pagination>
		</el-col>
<!--
  添加或修改页面
  visible.sync: 是否显示模态框
  :close-on-click-model:点空白处是否关模态框
  :rules="saveFormRules" form表单校验规则
  ref="saveForm" form表单的id

 -->
		<!--添加或修改界面-->
		<el-dialog :title="title"  :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px"  ref="saveForm" >

				<el-form-item label="角色">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="角色编号" >
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="权限" >
          <el-select v-model="saveForm.permissionIds" clearable  multiple placeholder="请选择">
            <el-option
                v-for="item in permissions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色菜单" >
          <el-cascader
              v-model="saveForm.menuIds"
              :options="menus"
              :props="{
                value:'id' ,label:'name',
                multiple:true,
                 emitPath:false}"
              clearable></el-cascader>
        </el-form-item>

      </el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>

import {title} from "mockjs/src/mock/random/text";
import th from "element-ui/src/locale/lang/th";
import jwt from 'jsonwebtoken';
export default {
	data() {
		return {

      options:[],//级联接收的数据
			//1.分页查询相关数据
			totals: 0,//总记录条数
			currentPage: 1,//当前页,要传递到后台的
			pageSize: 5, //每页显示多少条
			tableDatas: [], //当前页数据
			listLoading: false,

      //模态框标题
      title:"",
			//2.高级查询相关数据
			keyword: '',
      changeImgs:[], //定义一个数据，来记录我的附件框是否有值，如果有值，就证明有上传附件，如果没有值，就没有上传附件
			//3.删除相关数据

			//4.批量删除相关数据
			sels: [], //存储多选记录
      permissions:[],//所有的权限
      menus:[],//级联菜单
			//5.添加和修改相关数据
			saveFormVisible: false,
      //查询的form
      searchForm:{
        roleType:"", //文章类型
      },
			saveForm: {
        id: null,
       name:"",//角色名称
        sn:"",//角色编号
        permissionIds:[],//角色拥有的权限
        menuIds:[],//角色拥有的菜单

			},


		}
	},
  //自定义指令
  directives: {
    //指令名字 自己设定的 可以随便取
    permission: {
      // 指令的定义
      inserted: function (p1,p2,p3) {
        let token = localStorage.getItem("token");
        let resultObj = jwt.decode(token);
        let {permissions} = resultObj.payload;
        //只拿到permission中的sn  permission中的sn就是role：delete这种东西  而p2的值又恰好就是这个role：delete这个东西 需要判断它是sn中的那个 即v-permission="'role:delete'"是p2.value
        let permissionSns = permissions.map(k=>k.sn);
        //如果-1就代表不包含
        //如果权限sn当中没有找到sn 那么就删除p1这个按钮
        if(permissionSns.indexOf(p2.value)==-1){
          p1.parentNode.removeChild(p1);
        }

        //p1参数：dom节点 就是一个按钮
        //p2参数：能获取到传递的值
      }
    }
  },
	methods: {

		//1.分页查询相关方法
		//1.1.获取列表数据
		getTableData() {
      //开启加载框
      this.listLoading = true;
      //这一坨是负责传到后端的数据 记住前面双引号的名字需要和后端接收到的一样
			let param = {
        "currentPage": this.currentPage,
        "pageSize":this.pageSize,
      }
      this.$http.patch("/role",param).then(res=>{
        let {success,resultObj} = res.data;
        if(success){
           //关闭加载框
          this.listLoading = false;
          this.tableDatas = resultObj.list;
          this.totals = resultObj.total;
        }
      })
		},
		//1.2.选择第几页时触发
		handleCurrentChange(curentPage) {
			this.currentPage = curentPage;
      this.getTableData();
		},
		//1.3.选择每页显示记录条数时触发
		handleSizeChange(pageSize) {
			  this.currentPage = 1;
        this.pageSize = pageSize;
        this.getTableData();
		},

		//2.高级查询相关方法
		keywordQuery() {
      if(this.searchForm.date){
            this.searchForm.startTime =this.searchForm.date[0],
            this.searchForm.endTime = this.searchForm.date[1]
      }else {
            this.searchForm.startTime =null,
            this.searchForm.endTime = null
      }

			this.currentPage = 1;
      this.getTableData();
		},

		//3.删除相关方法
		handleDel(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete("/role/"+row.id).then(res=> {
          let {success} = res.data;
          if (success) {
            this.$message({
              type: 'success',
              message: "删除成功！"
            });
            //删除成功过后需要刷新
            this.getTableData();
          }else {
            this.$message.error(message);
          }
        })
      });
		},


		//4.批量删除相关方法
		//4.1.选项改变时触发
		handleSelectionChange(val) {
      this.sels = val;
		},
		//4.2.批量删除
    handlePatchDel() {
      this.$confirm('您确认删除选中的数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.patch("/role/patchDelete",this.sels).then(res=>{
          let  {success} = res.data;
          if(success){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getTableData();
          }
        })
      });
    },

		//5.添加和修改相关方法
		//5.1.点击添加弹出对话框
		handleAdd() {
      //设置标题
      this.title = "新增文章类型";
      //清空表单
      for(let k in this.saveForm){
        this.saveForm[k] = null;
      }
      //新增应该显示密码框
      this.saveForm["id"] = null;
      this.saveForm["topState"] = 1;
      this.saveForm["roleState"] = 0;
      //手动清空图片
      this.fileList = [];
      //弹出窗体
			 this.saveFormVisible = true;
		},
		//5.2.点击修改弹出对话框
		handleEdit(row) {
      //清空isChange的状态
      this.isChange = "";
      //修改标题
      this.title = "编辑角色类型";
      //清空表单
      for(let k in this.saveForm){
        this.saveForm[k] = "";

      }
    //回显数据
      for(let k in row){
        this.saveForm[k] = row[k];
      }
      this.saveForm.menuIds = row.menus.map(k=>k.id);
      this.saveForm.permissionIds = row.permissions.map(k=>k.id);
      console.log(this.saveForm)

    //打开模态框
      this.saveFormVisible = true
		},
		//5.3.提交表单数据操作数据库
    saveSubmit() {
      this.$http.post("/role",this.saveForm).then(res=>{
        let {success} = res.data;
        if(success){
          this.saveFormVisible = false;
          this.getTableData();
        }
      })
      },//获取权限的树形结构
    getPermissions(){
      this.$http.patch("/permission/list").then(res=>{
        let {success,resultObj} = res.data;
        if(success){
          this.permissions = resultObj;
        }
      });
    },
    //获取菜单的树形结构
    getMenus() {

      this.$http.patch("/menu/getTree").then(res=>{
        let{success,resultObj} = res.data;
        if(success){
          this.menus = resultObj;
        }
      })
    },
  },

	mounted() {

		this.getTableData();


    //获取权限
    this.getPermissions();
    //获取所有的菜单
    this.getMenus();


	}
}

</script>

<style scoped></style>
